<template>
  <div class="app-container">
    <header class="app-header">
      <h1>本地音乐播放器</h1>
      <button class="add-music-btn" @click="addMusic">
        添加音乐/视频
      </button>
    </header>

    <div class="main-content">
      <!-- 播放控制区域 -->
      <div class="player-section">
        <div class="album-cover">
          <video v-if="currentSong && currentSong.isVideo" :src="currentSong.path" class="video-player" controls></video>
          <img v-else-if="currentSong" src="/music-icon.png" alt="专辑封面" class="cover-image">
          <div v-else class="no-music">
            <span>暂无音乐</span>
          </div>
        </div>

        <div class="song-info">
          <h2 class="song-title">{{ currentSong ? currentSong.name : '请添加音乐' }}</h2>
          <div class="progress-container">
            <span class="time">{{ formatTime(currentTime) }}</span>
            <input 
              type="range" 
              v-model="seekPosition" 
              class="progress-bar"
              min="0" 
              :max="duration"
              @input="seekTo"
            >
            <span class="time">{{ formatTime(duration) }}</span>
          </div>
          <div class="volume-control">
            <span>🔊</span>
            <input 
              type="range" 
              v-model="volume" 
              class="volume-bar"
              min="0" 
              max="1"
              step="0.01"
              @input="setVolume"
            >
            <span>{{ Math.round(volume * 100) }}%</span>
          </div>
        </div>
      </div>

      <!-- 播放控制按钮 -->
      <div class="controls">
        <button @click="playPrevious" :disabled="!currentSong">
          ⏮️
        </button>
        <button @click="togglePlay" :disabled="!currentSong" class="play-btn">
          {{ isPlaying ? '⏸️' : '▶️' }}
        </button>
        <button @click="playNext" :disabled="!currentSong">
          ⏭️
        </button>
        <button @click="toggleRepeat" class="repeat-btn">
          {{ repeatMode === 'none' ? '🔁' : repeatMode === 'all' ? '🔁' : '🔂' }}
        </button>
        <button @click="toggleShuffle" :class="{ active: shuffleMode }">
          🔀
        </button>
      </div>

      <!-- 播放列表 -->
      <div class="playlist-section">
        <h2>播放列表</h2>
        <div class="playlist" v-if="playlist.length > 0">
          <div 
            v-for="(song, index) in playlist" 
            :key="song.path"
            class="playlist-item"
            :class="{ active: currentSongIndex === index }"
            @click="playSong(index)"
          >
            <span class="song-name">{{ song.name }}</span>
            <span class="song-duration">{{ formatFileSize(song.size) }}</span>
            <button class="remove-btn" @click.stop="removeSong(index)">
              ❌
            </button>
          </div>
        </div>
        <div v-else class="empty-playlist">
          播放列表为空，请添加音乐文件
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      playlist: [],
      currentSongIndex: -1,
      audio: null,
      isPlaying: false,
      currentTime: 0,
      duration: 0,
      volume: 0.7,
      repeatMode: 'none', // 'none', 'all', 'one'
      shuffleMode: false,
      shuffledIndices: []
    }
  },
  computed: {
    currentSong() {
      return this.currentSongIndex >= 0 && this.currentSongIndex < this.playlist.length
        ? this.playlist[this.currentSongIndex]
        : null
    },
    seekPosition: {
      get() {
        return this.currentTime
      },
      set(value) {
        this.currentTime = value
      }
    }
  },
  mounted() {
    // 初始化音频对象
    this.audio = new Audio()
    this.audio.volume = this.volume
    
    // 监听音频事件
    this.audio.addEventListener('timeupdate', this.updateTime)
    this.audio.addEventListener('loadedmetadata', this.updateDuration)
    this.audio.addEventListener('ended', this.handleSongEnd)
    
    // 检查本地存储中的播放列表
    this.loadPlaylist()
  },
  beforeUnmount() {
    // 清理事件监听
    if (this.audio) {
      this.audio.removeEventListener('timeupdate', this.updateTime)
      this.audio.removeEventListener('loadedmetadata', this.updateDuration)
      this.audio.removeEventListener('ended', this.handleSongEnd)
      this.audio.pause()
    }
  },
  methods: {
    // 添加音乐文件
    async addMusic() {
      try {
        const files = await window.electronAPI.selectMusicFiles()
        if (files && files.length > 0) {
          for (const filePath of files) {
            const songInfo = await window.electronAPI.getMusicInfo(filePath)
            if (songInfo && !this.playlist.some(song => song.path === filePath)) {
              this.playlist.push(songInfo)
            }
          }
          
          // 如果是第一次添加且没有当前播放的歌曲，自动播放第一首
          if (this.playlist.length > 0 && this.currentSongIndex === -1) {
            this.playSong(0)
          }
          
          // 保存播放列表到本地存储
          this.savePlaylist()
        }
      } catch (error) {
        console.error('添加音乐失败:', error)
      }
    },
    
    // 播放指定歌曲
    playSong(index) {
      if (index >= 0 && index < this.playlist.length) {
        this.currentSongIndex = index
        const song = this.playlist[index]
        
        // 如果是视频文件，不需要通过audio标签播放（直接在video元素中播放）
        if (!song.isVideo) {
          this.audio.src = song.path
          this.audio.play().then(() => {
            this.isPlaying = true
          }).catch(error => {
            console.error('播放失败:', error)
          })
        } else {
          this.isPlaying = true
        }
      }
    },
    
    // 切换播放/暂停
    togglePlay() {
      if (!this.currentSong) return
      
      if (this.currentSong.isVideo) {
        // 对于视频，直接控制video元素
        const video = document.querySelector('.video-player')
        if (video) {
          if (this.isPlaying) {
            video.pause()
          } else {
            video.play()
          }
          this.isPlaying = !this.isPlaying
        }
      } else {
        // 对于音频
        if (this.isPlaying) {
          this.audio.pause()
        } else {
          this.audio.play()
        }
        this.isPlaying = !this.isPlaying
      }
    },
    
    // 播放上一首
    playPrevious() {
      if (this.playlist.length === 0) return
      
      if (this.shuffleMode) {
        // 随机播放模式
        if (this.shuffledIndices.length === 0 || this.currentSongIndex === 0) {
          this.generateShuffledIndices()
          this.playSong(this.shuffledIndices[0])
        } else {
          const currentShuffledIndex = this.shuffledIndices.indexOf(this.currentSongIndex)
          const prevShuffledIndex = currentShuffledIndex > 0 ? currentShuffledIndex - 1 : this.shuffledIndices.length - 1
          this.playSong(this.shuffledIndices[prevShuffledIndex])
        }
      } else {
        // 顺序播放模式
        let newIndex = this.currentSongIndex - 1
        if (newIndex < 0) {
          newIndex = this.playlist.length - 1
        }
        this.playSong(newIndex)
      }
    },
    
    // 播放下一首
    playNext() {
      if (this.playlist.length === 0) return
      
      if (this.shuffleMode) {
        // 随机播放模式
        if (this.shuffledIndices.length === 0 || this.currentSongIndex === this.shuffledIndices[this.shuffledIndices.length - 1]) {
          this.generateShuffledIndices()
          this.playSong(this.shuffledIndices[0])
        } else {
          const currentShuffledIndex = this.shuffledIndices.indexOf(this.currentSongIndex)
          const nextShuffledIndex = currentShuffledIndex < this.shuffledIndices.length - 1 ? currentShuffledIndex + 1 : 0
          this.playSong(this.shuffledIndices[nextShuffledIndex])
        }
      } else {
        // 顺序播放模式
        let newIndex = this.currentSongIndex + 1
        if (newIndex >= this.playlist.length) {
          newIndex = 0
        }
        this.playSong(newIndex)
      }
    },
    
    // 移除歌曲
    removeSong(index) {
      if (index >= 0 && index < this.playlist.length) {
        // 如果移除的是当前播放的歌曲
        if (index === this.currentSongIndex) {
          const wasPlaying = this.isPlaying
          if (this.playlist.length > 1) {
            // 如果还有其他歌曲，播放下一首
            this.playNext()
          } else {
            // 如果是最后一首歌，停止播放
            this.audio.pause()
            this.isPlaying = false
            this.currentTime = 0
            this.duration = 0
            this.currentSongIndex = -1
          }
        } else if (index < this.currentSongIndex) {
          // 如果移除的是当前歌曲之前的歌曲，更新索引
          this.currentSongIndex--
        }
        
        this.playlist.splice(index, 1)
        this.savePlaylist()
      }
    },
    
    // 切换重复模式
    toggleRepeat() {
      const modes = ['none', 'all', 'one']
      const currentIndex = modes.indexOf(this.repeatMode)
      this.repeatMode = modes[(currentIndex + 1) % modes.length]
    },
    
    // 切换随机播放
    toggleShuffle() {
      this.shuffleMode = !this.shuffleMode
      if (this.shuffleMode) {
        this.generateShuffledIndices()
      }
    },
    
    // 生成随机索引
    generateShuffledIndices() {
      this.shuffledIndices = [...Array(this.playlist.length).keys()]
      // Fisher-Yates 洗牌算法
      for (let i = this.shuffledIndices.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[this.shuffledIndices[i], this.shuffledIndices[j]] = [this.shuffledIndices[j], this.shuffledIndices[i]]
      }
    },
    
    // 更新时间
    updateTime() {
      this.currentTime = this.audio.currentTime
    },
    
    // 更新时长
    updateDuration() {
      this.duration = this.audio.duration
    },
    
    // 跳转到指定位置
    seekTo() {
      if (this.audio) {
        this.audio.currentTime = this.currentTime
      }
    },
    
    // 设置音量
    setVolume() {
      if (this.audio) {
        this.audio.volume = this.volume
      }
    },
    
    // 处理歌曲结束
    handleSongEnd() {
      if (this.repeatMode === 'one') {
        // 单曲循环
        this.audio.currentTime = 0
        this.audio.play()
      } else {
        // 播放下一首
        this.playNext()
      }
    },
    
    // 格式化时间
    formatTime(seconds) {
      if (!seconds || isNaN(seconds)) return '00:00'
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes < 1024) return bytes + ' B'
      else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'
      else return (bytes / 1048576).toFixed(1) + ' MB'
    },
    
    // 保存播放列表
    savePlaylist() {
      try {
        localStorage.setItem('musicPlayerPlaylist', JSON.stringify(this.playlist))
      } catch (error) {
        console.error('保存播放列表失败:', error)
      }
    },
    
    // 加载播放列表
    loadPlaylist() {
      try {
        const savedPlaylist = localStorage.getItem('musicPlayerPlaylist')
        if (savedPlaylist) {
          this.playlist = JSON.parse(savedPlaylist)
        }
      } catch (error) {
        console.error('加载播放列表失败:', error)
      }
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  background-color: #f5f5f5;
  color: #333;
}

.app-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-header {
  background-color: #333;
  color: white;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-music-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.add-music-btn:hover {
  background-color: #45a049;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 1rem;
  gap: 1rem;
}

.player-section {
  display: flex;
  gap: 1rem;
  background-color: white;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.album-cover {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-player {
  width: 100%;
  height: 100%;
}

.no-music {
  font-size: 1.5rem;
  color: #999;
}

.song-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 1rem;
}

.song-title {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.progress-bar {
  flex: 1;
  height: 4px;
  background-color: #ddd;
  border-radius: 2px;
  outline: none;
  cursor: pointer;
}

.time {
  font-size: 0.8rem;
  color: #666;
  min-width: 45px;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 200px;
}

.volume-bar {
  flex: 1;
  height: 4px;
  background-color: #ddd;
  border-radius: 2px;
  outline: none;
  cursor: pointer;
}

.controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.controls button {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.controls button:hover:not(:disabled) {
  background-color: #f0f0f0;
}

.controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.play-btn {
  font-size: 2rem;
  background-color: #4CAF50;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 50%;
}

.play-btn:hover:not(:disabled) {
  background-color: #45a049;
}

.repeat-btn.active,
.shuffle-mode.active {
  background-color: #f0f0f0;
}

.playlist-section {
  flex: 1;
  background-color: white;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.playlist-section h2 {
  margin-bottom: 1rem;
}

.playlist {
  flex: 1;
  overflow-y: auto;
}

.playlist-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s;
}

.playlist-item:hover {
  background-color: #f9f9f9;
}

.playlist-item.active {
  background-color: #e3f2fd;
  color: #1976d2;
}

.song-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 1rem;
}

.song-duration {
  margin-right: 1rem;
  color: #666;
  font-size: 0.9rem;
}

.remove-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1rem;
  opacity: 0.5;
  transition: opacity 0.3s;
}

.remove-btn:hover {
  opacity: 1;
}

.empty-playlist {
  text-align: center;
  color: #999;
  padding: 2rem;
}
</style>